package com.baselibrary.extension

import android.content.Context
import android.content.res.AssetManager
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.text.Editable
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.util.TypedValue
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.baselibrary.utils.CommonUtil
import com.baselibrary.utils.DslSpannableStringBuilderImpl
import com.baselibrary.view.customtablayout.BaseIndicator
import com.baselibrary.view.customtablayout.BaseText
import com.google.android.material.tabs.TabLayout


/**
 * @author merbng
 * @date 2018/1/9
 */

fun Any?.checkNotNull(): Boolean {
    return CommonUtil.isNotEmpty(this)
}

fun AppCompatActivity.getResColor(@ColorRes id: Int): Int {
    return ContextCompat.getColor(this, id)
}

//渐变的shape背景
fun TextView.setGradientBackground(tv: TextView, radius: Float = 50f, textColor: String = "#FFFFFF", startColor: String = "#CE47F2", endColor: String = "#6F0CF8") {
    // 创建渐变的shape drawable
    val colors = intArrayOf(Color.parseColor(startColor), Color.parseColor(endColor))//分别为开始颜色，中间夜色，结束颜色
    val gradientDrawable = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors)
    gradientDrawable.setCornerRadius(radius)
    tv.setBackgroundDrawable(gradientDrawable)
    tv.setTextColor(Color.parseColor(textColor))
}

fun TextView.setDefTTF(context: Context) {
    val mgr: AssetManager = context.assets //得到AssetManager
    val tf = Typeface.createFromAsset(mgr, "fonts/home_tab.ttf") //根据路径得到Typeface
    this.typeface = tf //设置字体

}

//商城价格字体
fun TextView.setMallPriceTTF(context: Context) {
    val mgr: AssetManager = context.assets //得到AssetManager
    val tf = Typeface.createFromAsset(mgr, "fonts/mall_price.ttf") //根据路径得到Typeface
    this.typeface = tf //设置字体
}

interface DslSpannableStringBuilder {
    //增加一段文字
    fun addText(text: String, method: (DslSpanBuilder.() -> Unit)? = null)
}

interface DslSpanBuilder {
    //设置文字颜色
    fun setColor(color: String)

    //设置点击事件
    fun onClick(useUnderLine: Boolean = true, onClick: (View) -> Unit)
}

/*【使用实例】
tvTestDsl.buildSpannableString {
    addText("我已详细阅读并同意")
    addText("《隐私政策》"){
        setColor("#0099FF")
        onClick(false) {
            //do some thing
        }
    }
}
* */
//为 TextView 创建扩展函数，其参数为接口的扩展函数
fun TextView.buildSpannableString(init: DslSpannableStringBuilder.() -> Unit) {
    //具体实现类
    val spanStringBuilderImpl = DslSpannableStringBuilderImpl()
    spanStringBuilderImpl.init()
    movementMethod = LinkMovementMethod.getInstance()
    //通过实现类返回SpannableStringBuilder
    text = spanStringBuilderImpl.build()
}

inline fun EditText.addTextChangedListenerClosure(crossinline afterTextChanged: (Editable?) -> Unit = {}, crossinline beforeTextChanged: (CharSequence?, Int, Int, Int) -> Unit = { charSequence, start, count, after -> }, crossinline onTextChanged: (CharSequence?, Int, Int, Int) -> Unit = { charSequence, start, after, count -> }) {
    val listener = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            afterTextChanged.invoke(s)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            beforeTextChanged.invoke(s, start, count, after)
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            onTextChanged.invoke(s, start, before, count)
        }
    }
    this.addTextChangedListener(listener)
}

fun Int.num99(): String {
    if (this > 99) {
        return ("99+")
    } else {
        return (this.toString())
    }
}

/**
 * px转dp
 */
fun Context.px2dip(px: Float): Float = px / resources.displayMetrics.density + 0.5f

fun Context.px2dip(px: Int): Int = px2dip(px.toFloat()).toInt()

/**
 * dp转px
 */
fun Context.dip2px(dp: Float): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics)

fun Context.dip2px(dp: Int): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), resources.displayMetrics).toInt()
fun Float.dp2px(context: Context) : Float {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        this,
        context.resources.displayMetrics
    )
}
/**
 * sp转px
 */
fun Context.sp2px(sp: Float): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, resources.displayMetrics)

fun Context.sp2px(sp: Int): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), resources.displayMetrics).toInt()

/**
 * 绑定tabLayout指示器
 */
inline fun <reified T : BaseIndicator> TabLayout.buildIndicator(): T {
    val indicator = T::class.java.newInstance()
    indicator.bindTabLayout(this)
    return indicator
}

/**
 * 绑定tabLayout文字设置
 */
inline fun <reified T : BaseText> TabLayout.buildText(): T {
    val text = T::class.java.newInstance()
    text.bindTabLayout(this)
    return text
}
